import type { Directive, DirectiveBinding } from 'vue';
import type { WatermarkOptions } from '../types/watermark';

const defaultOptions: Required<WatermarkOptions> = {
  text: '机密文档',
  font: '16px Microsoft YaHei',
  color: 'rgba(128, 128, 128, 0.6)',
  width: 300,
  height: 200,
  rotate: -20,
  opacity: 0.6,
  zIndex: 9999
};

const createWatermarkImage = (options: Required<WatermarkOptions>): string => {
  const canvas = document.createElement('canvas');
  canvas.width = options.width;
  canvas.height = options.height;
  
  const ctx = canvas.getContext('2d');
  if (!ctx) return '';
  
  // 设置画布属性
  ctx.rotate((options.rotate * Math.PI) / 180);
  ctx.font = options.font;
  ctx.fillStyle = options.color;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.globalAlpha = options.opacity;

  // 处理多行文本
  const texts = Array.isArray(options.text) ? options.text : [options.text];
  const lineHeight = options.height / (texts.length + 1);
  
  texts.forEach((text, index) => {
    ctx.fillText(text, options.width / 2, lineHeight * (index + 1));
  });

  return canvas.toDataURL('image/png');
};

const watermarkDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<WatermarkOptions>) {
    const options: Required<WatermarkOptions> = {
      ...defaultOptions,
      ...binding.value
    };

    // 创建水印元素
    const watermarkElement = document.createElement('div');
    watermarkElement.className = 'vue-watermark';
    
    const style = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      background-repeat: repeat;
      z-index: ${options.zIndex};
      background-image: url('${createWatermarkImage(options)}');
    `;
    
    watermarkElement.setAttribute('style', style);
    el.appendChild(watermarkElement);
    el.style.position = 'relative';

    // 防篡改监听
    const observer = new MutationObserver(() => {
      const watermark = el.querySelector('.vue-watermark');
      if (!watermark || watermark.getAttribute('style') !== style) {
        observer.disconnect();
        watermarkDirective.mounted(el, binding);
      }
    });

    observer.observe(el, {
      attributes: true,
      childList: true,
      subtree: true
    });

    // 保存观察者实例以便卸载时清除
    el._watermarkObserver = observer;
  },
  
  unmounted(el: HTMLElement & { _watermarkObserver?: MutationObserver }) {
    if (el._watermarkObserver) {
      el._watermarkObserver.disconnect();
    }
    const watermark = el.querySelector('.vue-watermark');
    if (watermark) {
      el.removeChild(watermark);
    }
  },
  
  updated(el: HTMLElement, binding: DirectiveBinding<WatermarkOptions>) {
    watermarkDirective.unmounted(el);
    watermarkDirective.mounted(el, binding);
  }
};

export default watermarkDirective;